<?php
namespace app\controller;

use think\Controller;
use Overtrue\PHPOpenCC\OpenCC;
use app\service\R2Service;

class Publish extends Controller
{
    private $_url = [
        
        ['https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list',
        '{"login_info":{},"cate_id":1,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        1],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list',
        '{"login_info":{},"cate_id":8,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        10],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":9,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        7],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":7,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        5],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":4,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        3],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":12,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        11],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":10,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        6],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":13,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        13],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":2,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        2],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":6,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        12],
        [
        'https://pcwallpaper.zhhainiao.com/mobile/wallpaper/static/list','
        {"login_info":{},"cate_id":5,"page":%page%,"page_size":100,"common":{"open_id":"1495252643152400384","token":"25e23da1a18b1729418ce612726ed1f977f05bdb","device_id":"dac76e2ccda083212335010848c18924","player_version":112,"platform":"pc"}}',
        9],
    ];

    public function remove_noindex($type = 'all',$category_id = 0,$cnt = 3){
        $cache_category_key_base = 'last_update_time_category_id_';
        $cache_top_category_key_base = 'last_update_time_top_category_';
        $type_arr = [];
        $where = ['noindex'=>1];
        if ($type != 'all'){
            $where['type'] = $type;
        }
        if ($category_id != 0){
            $where['category_id'] = $category_id;
        }
        $data = db('wallpaper')->where($where)->orderRaw('rand()')->limit($cnt)->select();
        $ids = implode(',',array_column($data,'id'));
        foreach ($data as $value) {
            $title = $value['title'];
            $category_id = $value['category_id'];
            $type = $value['type'];
            $type_arr[] = $type;
            
            db('wallpaper')->where('title',$title)->update(['noindex'=>0,'update_time'=>date('Y-m-d H:i:s')]);
            
            $cache_category_key = $cache_category_key_base.$category_id .'_'.$type;
            cache($cache_category_key,date('Y-m-d'),['expire' => 0]);
            
            echo "{$ids} {$value['title']} {$cache_category_key}: " . cache($cache_category_key) . " success\n";
            
        }
        $type_arr = array_unique($type_arr);
        foreach ($type_arr as $type) {
            $cache_top_category_key = $cache_top_category_key_base.$type;
            cache($cache_top_category_key,date('Y-m-d'),['expire' => 0]);
        }
        

    }

    public function run_index($category_id){
        $category_ids = array_column($this->_url,2);
        if (!in_array($category_id,$category_ids)){
            echo "category_id {$category_id} not found\n";
            exit();
        }
        $index = array_search($category_id,$category_ids);
		$this->_run($this->_url[$index]);
	}

    public function run_all(){
        foreach ($this->_url as $value) {
            for ($i=0; $i < 20; $i++) { 
                $this->_run($value);
            }
        }
    }
    private function _run($current){
        $page = 1;
        $spider_source = 'zhhainiao';
        echo "page {$page} cate_id {$current[2]}\n";
        $url = $current[0];
        $post_base = $current[1];
        $cate_id = $current[2];
        while (1){
            $post = str_replace("%page%", $page, $post_base);
            $contents = curl_post($url,$post);
            $contents = json_decode($contents,true);
            if (empty($contents['data']['list'])) {
                echo "没有数据\n";
                return false;
            }
            foreach ($contents['data']['list'] as $value) {
                $title = $value['wname'];
                if (empty($title)) {
                    $title = str_replace('#', '', $value['tags_str']);
                }
                $title = removeAllBracketsContent($title);
                $title = str_replace([',','，'], ' ', $title);
                $title = trim($title);
                if (empty($title)) {
                    continue;
                }
                $spider_id = $value['id'];
                $exits = db('wallpaper')
                    ->where([
                        'spider_id'=>$spider_id,
                        'spider_source'=>$spider_source])
                    ->find();
                //var_dump($spider_id,$exits);exit;
                
                if (!empty($exits)) {
                    echo "title {$title} repeat noindex {$exits['noindex']}\n";
                    continue;
                }
                $title = openCC::simplifiedToTaiwan($title);

                $pic_640 = isset($value['mobile_file_640'])?urldecode($value['mobile_file_640']):'';
                $pic_1k = isset($value['mobile_file_1k'])?urldecode($value['mobile_file_1k']):'';
                $pic_2k = isset($value['mobile_file_2k'])?urldecode($value['mobile_file_2k']):'';
                $pic_4k = isset($value['mobile_file_4k'])?urldecode($value['mobile_file_4k']):'';
                
                $local_640 = download($pic_640);
                $local_1k = download($pic_1k);
                $local_2k = download($pic_2k);
                $local_4k = download($pic_4k);

                if (empty($local_640) && empty($local_1k) && empty($local_2k) && empty($local_4k)){
                    continue;
                }
                $r2Service = new R2Service();
                $local_640_full_path = 'res'.$local_640;
                $local_1k_full_path = 'res'.$local_1k;
                $local_2k_full_path = 'res'.$local_2k;
                $local_4k_full_path = 'res'.$local_4k;
                $local_640 = $r2Service->uploadFile($local_640_full_path);
                $local_1k = $r2Service->uploadFile($local_1k_full_path);
                $local_2k = $r2Service->uploadFile($local_2k_full_path);
                $local_4k = $r2Service->uploadFile($local_4k_full_path);
                
                
                $pic = [ 
                    '640'	=> $local_640,
                    '1k'	=> $local_1k,
                    '2k'	=> $local_2k,
                    '4k'	=> $local_4k,
                ];

                $value['tags_str'] = explode(',', $value['tags_str']);
                $value['tags_str'] = array_unique($value['tags_str']);
                $tag_name = implode(',', $value['tags_str']);
                
                $title_simplify = filter_non_text_chars($title);

                $noindex_wallpaper = db('wallpaper')->where('title',$title)->where('status',1)->where('noindex',0)->find();
                $noindex = 1;
                if (!empty($noindex_wallpaper)){
                    $noindex = 0;
                }
                $id = db('wallpaper')->insertGetId([
                    'title'         => $title,
                    'title_simplify'=> $title_simplify,
                    'type'          => 'mobile',
                    'category_id'   => $cate_id,
                    'tag_name'      => $tag_name,
                    'noindex'       => $noindex,
                    'file_path'     => json_encode($pic,JSON_UNESCAPED_UNICODE),
                    'create_time'   => date('Y-m-d H:i:s'),
                    'update_time'   => date('Y-m-d H:i:s'),
                    'spider_source' => $spider_source,
                    'spider_id'     => $spider_id,
                    'title_id'      => 0,
                ]);

                if (!$id){
                    echo "title {$title} noindex {$noindex} insert failed\n";
                    exit();
                }
                
                echo "title {$title} noindex {$noindex} success\n";
                return true;
            }
            ++$page;
        }
		
    }
}